package com.zh.oauth.controller;

import com.alibaba.fastjson.JSON;
import com.zh.common.constans.AuthConstant;
import com.zh.common.entity.ElecSmsEntity;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.ElecMenu;
import com.zh.common.util.SendSMSUtil;
import com.zh.oauth.dao.AuthMapper;
import com.zh.oauth.entity.ElecAuth;
import com.zh.oauth.entity.ElecUser;
import com.zh.oauth.entity.ElecRole;
import com.zh.oauth.service.AuthService;
import com.zh.oauth.service.ElecUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;


import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 权限控制管理
 * @Author: Li.HuiNeng
 * @Create in: 2019/10/14
 * @Version: 1.0.1
 */
@Api(value = "权限控制管理控制器", produces = "application/json", tags = {"权限控制管理控制器"})
@RestController
@RequestMapping("/authManage")
public class AuthController {

    /**
     * @Description: 简易crud时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/10/14
     */
    @Autowired
    private AuthMapper authMapper;

    /**
     * @Description: 有业务逻辑需要处理时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/10/14
     */
    @Autowired
    private AuthService authService;

    /**
     * @Description: redis实例
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/10/14
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ElecUserService userService;

    @ApiOperation(value = "新增一条记录", tags = {"putElecAuth"}, notes = "新增一条记录")
    @PutMapping("/putElecAuth")
    public JSONResult<Object> putElecAuth(@ApiParam(value = "权限控制实体类", name = "ElecAuth") ElecAuth auth) {
        ElecUser user = (ElecUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JSONResult<Object> jsonResult = new JSONResult<>();
        // 添加时默认的值
        auth.setAuthOp(user.getUserLoginName());
        try {
            if (auth.insert()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("添加失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "通过id修改信息", tags = {"updateElecAuthById"}, notes = "通过id修改信息")
    @PutMapping("/updateElecAuthById")
    public JSONResult<Object> updateElecAuthById(@ApiParam(value = "权限控制实体类", name = "ElecAuth") ElecAuth elecAuth) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            if (elecAuth.updateById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("修改完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("修改失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据主键删除记录", tags = {"deleteElecAuthById"}, notes = "根据主键删除记录")
    @DeleteMapping("/deleteElecAuthById")
    public JSONResult<Object> deleteElecAuthById(@ApiParam(value = "权限控制实体类", name = "ElecAuth") ElecAuth elecAuth) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            if (elecAuth.deleteById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据主键列表批量删除记录", tags = {"deleteElecAuthBatchByIds"}, notes = "该传参时 请选择raw(application/json)格式传入")
    @DeleteMapping("/deleteElecAuthBatchByIds")
    public JSONResult<Object> deleteElecAuthBatchByIds(@ApiParam(value = "主键集合", name = "ids") @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int c = this.authMapper.deleteBatchIds(ids);
            if (c > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据id查询详细信息", tags = {"getElecAuthById"}, notes = "根据id查询详细信息")
    @GetMapping("/getElecAuthById")
    public JSONResult<Object> getElecAuthById(@ApiParam(value = "权限控制实体类", name = "ElecAuth") ElecAuth ElecAuth) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            ElecAuth result = ElecAuth.selectById(ElecAuth.getId());
            if (result != null) {
                jsonResult.setCode(200);
                jsonResult.setMessage("查询完成");
                jsonResult.setSuccess(true);
                jsonResult.setData(result);
            } else {
                jsonResult.setMessage("未查询到相应信息，请检查参数是否正确");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "获取角色列表信息", tags = {"getRoleList"}, notes = "获取角色列表信息")
    @GetMapping("/getRoleList")
    public JSONResult<Object> getRoleList() {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            ElecRole role = new ElecRole();
            // 获取角色类型列表
            List<ElecRole> list = role.selectList(null);
            jsonResult.setData(list);
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取验证码", tags = {"getCaptcha"}, notes = "获取验证码")
    @GetMapping("/getCaptcha")
    public JSONResult<Object> getCaptcha(@RequestParam(value = "phoneNumber") @NotNull(message = "请填写手机号") String phoneNumber) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        if (StringUtils.isEmpty(phoneNumber) || phoneNumber.equals("null")) {
            jsonResult.setMessage("请填写手机号.");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
        try {
            ElecSmsEntity smsEntity = authMapper.sendSms(1L);
            smsEntity.setPhoneNumber(phoneNumber);
            jsonResult = SendSMSUtil.sendSms(smsEntity);
            Map map = (Map) jsonResult.getData();
            if (Objects.isNull(map)) {
               return jsonResult;
            }
            // 验证码保存五分钟
            redisTemplate.opsForValue().set(phoneNumber, map.get("Captcha"), 5, TimeUnit.MINUTES);
        } catch (Exception e) {
            jsonResult.setMessage("请填写正确的手机号!");
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "/getAuthRoleTree", notes = "获取角色、菜单、权限树")
    @GetMapping("/getAuthRoleTree")
    public JSONResult<Object> getAuthRoleTree(@NotEmpty(message = "操作用户名不能为空") @RequestParam("uName") String uName) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        Map<String, Object> map = new HashMap<>();
        try {
            List<ElecAuth> authList = JSON.parseArray(JSON.toJSONString(redisTemplate.opsForValue().get(uName + AuthConstant.REDIS_AUTH_TREE)), ElecAuth.class);
            List<ElecMenu> menuList = JSON.parseArray(JSON.toJSONString(redisTemplate.opsForValue().get(uName + AuthConstant.REDIS_WEB_MENU_KEY)), ElecMenu.class);
            List<ElecRole> roleList = JSON.parseArray(JSON.toJSONString(redisTemplate.opsForValue().get(uName + AuthConstant.USER_ROLE)), ElecRole.class);
            map.put("menu", menuList);
            map.put("auth", authList);
            map.put("role", roleList);
            jsonResult.setSuccess(true);
            jsonResult.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取指定角色权限id", tags = {"getAuthListByRoleId"}, notes = "获取指定角色权限id")
    @GetMapping("/getAuthListByRoleId")
    public JSONResult<Object> getAuthListByRoleId(Long roleId) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            Map<String, Object> map = userService.getAuthListByRoleId(roleId);
            if (Objects.nonNull(map)) {
                String[] list = map.get("authId").toString().split(",");
                jsonResult.setData(list);
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("该角色权限为空,请检查是否绑定权限信息!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "添加角色信息", tags = {"addRole"}, notes = "添加角色信息")
    @PutMapping("/addRole")
    public JSONResult<Object> addRole(@NotEmpty(message = "操作用户名不能为空") String uName, ElecRole role) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            authService.addRole(role);
            if (role.getSuccess() > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setData(role.getId());
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "删除角色信息", tags = {"delRole"}, notes = "删除角色信息")
    @DeleteMapping("/delRole")
    public JSONResult<Object> delRole(Long id, @NotEmpty(message = "操作用户名不能为空") String uName) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            int i = authService.delRole(id);
            if (i > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改角色信息", tags = {"modRole"}, notes = "修改角色信息")
    @PutMapping("/modRole")
    public JSONResult<Object> modRole(@NotEmpty(message = "操作用户名不能为空") String uName, ElecRole role) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            int i = authService.modRole(role);
            if (i > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "添加权限信息", tags = {"addAuth"}, notes = "添加权限信息")
    @PutMapping("/addAuth")
    public JSONResult<Object> addAuth(@NotEmpty(message = "操作用户名不能为空") String uName, ElecAuth auth) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            auth.setAuthOp(uName);
            authService.addAuth(auth);
            if (auth.getId() > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setData(auth.getId());
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "删除权限信息", tags = {"delRodelAuthle"}, notes = "删除权限信息")
    @DeleteMapping("/delAuth")
    public JSONResult<Object> delAuth(@NotEmpty(message = "操作用户名不能为空") String uName, ElecAuth elecAuth) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            authService.delAuth(elecAuth);
            if (elecAuth.getDeleted() > 0) {
                jsonResult.setMessage("操作完成!");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("操作失败！");
                jsonResult.setSuccess(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改权限信息", tags = {"modAuth"}, notes = "修改权限信息")
    @PutMapping("/modAuth")
    public JSONResult<Object> modAuth(@NotEmpty(message = "操作用户名不能为空") String uName, ElecAuth auth) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            int i = authService.modAuth(auth);
            if (i > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setData(auth.getId());
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "添加菜单信息", tags = {"addMenu"}, notes = "添加菜单信息")
    @PutMapping("/addMenu")
    public JSONResult<Object> addMenu(@NotEmpty(message = "操作用户名不能为空") String uName, ElecMenu menu) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            menu.setMenuOp(uName);
            authService.addMenu(menu);
            if (menu.getId() > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setData(menu.getId());
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "删除菜单信息", tags = {"delMenu"}, notes = "删除菜单信息")
    @DeleteMapping("/delMenu")
    public JSONResult<Object> delMenu(@NotEmpty(message = "操作用户名不能为空") String uName, ElecMenu menu) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            authService.delMenu(menu);
            if (menu.getDeleted() > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改菜单信息", tags = {"modMenu"}, notes = "修改菜单信息")
    @PutMapping("/modMenu")
    public JSONResult<Object> modMenu(@NotEmpty(message = "操作用户名不能为空") String uName, ElecMenu menu) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            int i = authService.modMenu(menu);
            if (i > 0) jsonResult.setMessage("操作完成!");
            else jsonResult.setMessage("操作失败！");
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "绑定账户角色", tags = {"bindRoleAc"}, notes = "绑定账户角色")
    @PutMapping("/bindRoleAc")
    public JSONResult<Object> bindRoleAc(@NotEmpty(message = "操作用户名不能为空") String uName,
                                         @RequestParam(required = false)String tag,
                                         @NotEmpty(message = "请选择需要操作的角色")String roleId,
                                         @RequestParam(required = false,defaultValue = "")String authIds,
                                         @RequestParam(required = false,defaultValue = "")String menuIds,
                                         @RequestParam(required = false,defaultValue = "")String userParam) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        TreeMap<String, String> map = new TreeMap<>();
        map.put("tag", tag);
        map.put("roleId", roleId);
        map.put("authId",authIds);
        map.put("menuId",menuIds);
        map.put("userParam",userParam);
        try {
            authService.bindRoleAc(map);
            if (map.get("success").equals("-1")) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("用户不存在，请检查用户名或手机号是否正确!");
            } else
                jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }




    @ApiOperation(value = "注册", tags = {"register"}, notes = "注册")
    @PutMapping("/register")
    @ResponseBody
    public JSONResult<Object> register(@RequestBody ElecUser elecUser) {
        // 获取验证码
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        String Captcha = (String) redisTemplate.opsForValue().get(elecUser.getUserMobile());
        if (StringUtils.isEmpty(Captcha)) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("验证码失效!");
            return jsonResult;
        }
        if (!Captcha.equals(elecUser.getCaptcha())) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("验证码不正确,请重新请求!");
            return jsonResult;
        }
        elecUser.setUserPassword(new BCryptPasswordEncoder().encode(elecUser.getUserPassword()));
        elecUser.setUserRegTime(new Date());
        if (userService.registerUser(elecUser)) {
            jsonResult.setSuccess(true);
            jsonResult.setMessage("注册成功!");
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("注册失败!");
        }
        return jsonResult;
    }


    @ApiOperation(value = "验证用户名是否被占用", tags = {"getUserByName"}, notes = "验证用户名是否被占用")
    @GetMapping("/getUserByName")
    public JSONResult<Object> getUserByName(@ApiParam(value = "userLoginName", name = "用户账户名") String userLoginName) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        int i = userService.getUserByName(userLoginName);
        if (i > 0) {
            jsonResult.setSuccess(true);
            jsonResult.setMessage("该用户名已注册!请重新填写");
        } else
            jsonResult.setSuccess(false);
        return jsonResult;
    }


    @ApiOperation(value = "验证手机号是否被占用", tags = {"getMobileAysValid"}, notes = "验证手机号是否被占用")
    @GetMapping("/getMobileAysValid")
    public JSONResult<Object> getMobileAysValid(@ApiParam(value = "mobile", name = "手机号") String mobile) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        int i = userService.getMobileAysValid(mobile);
        if (i > 0) {
            jsonResult.setSuccess(true);
            jsonResult.setMessage("该手机号以注册!请重新填写");
        } else
            jsonResult.setSuccess(false);
        return jsonResult;
    }

//    @ApiOperation(value = "绑定权限", tags = {"bindUserAuth"}, notes = "绑定权限")
//    @PutMapping("/bindUserAuth")
//    public JSONResult<Object> bindUserAuth(
//            @ApiParam(value = "authIds", name = "权限节点集合") String authIds,
//            @ApiParam(value = "authIds", name = "菜单节点集合") String menuIds,
//            @ApiParam(value = "roleNo", name = "角色编号")String roleNo,
//            @ApiParam(value = "roleId", name = "所属角色")String roleId,
//            @ApiParam(value = "roleType", name = "角色类型")String roleType,
//            @ApiParam(value = "userParam", name = "用户账户名或手机号") String userParam) {
//        JSONResult<Object> jsonResult = new JSONResult<>();
//        int b = userService.bindUserAuth(authIds,menuIds,roleId,roleType,roleNo,userParam);
//        if (b > 0) {
//            jsonResult.setSuccess(true);
//            jsonResult.setMessage("用户权限绑定完成!");
//        } else if (b == -1){
//            jsonResult.setSuccess(false);
//            jsonResult.setMessage("绑定失败，请检查用户账户名或手机号是否存在!");
//        } else if (b == -2){
//            jsonResult.setSuccess(false);
//            jsonResult.setMessage("绑定失败,用户角色出现异常，请检查是否选择正确角色！");
//        } else if (b == -3) {
//            jsonResult.setSuccess(false);
//            jsonResult.setMessage("绑定失败,绑定用户与角色身份属性错误！");
//        }
//        return jsonResult;
//    }


}
